package cn.itcode_03;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @author Aaron
 * @since 2021/3/22 17:19
 * <p>描述：</p>
 */
public class Piped {

    public static void main(String[] args) throws IOException {
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();
        // 将输出流和输入流连接起来，否则使用时会抛出 IOException 异常
        out.connect(in);

        Thread printThread = new Thread(new Print(in), "PrintThread");
        printThread.start();
        int receive = 0;
        try {
            while ((receive = System.in.read()) != -1) {
                System.out.println(Thread.currentThread().getName() + " - " + (char) receive);
                out.write(receive);
            }
        } finally {
            out.close();
        }
    }

    static class Print implements Runnable {

        private final PipedReader in;

        public Print(PipedReader in) {
            this.in = in;
        }

        @Override
        public void run() {
            int receive = 0;
            try {
                while ((receive = in.read()) != -1) {
                    System.out.println(Thread.currentThread().getName() + " - " + (char) receive);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
